//
//  YNHttpTool.m
//  gold_ios_carteam
//
//  Created by 张伟 on 2018/5/22.
//  Copyright © 2018年 张伟. All rights reserved.
//

#import "YNHttpTool.h"

#import <AdSupport/AdSupport.h>
#import <CommonCrypto/CommonDigest.h>
#define securityCode @"e0ahndwscm90&mxd4n^vpi7vx!s5l0b"

static YNHttpTool *sharedManager=nil; //放入外部
static AFHTTPSessionManager* manager;
@implementation YNHttpTool


+(instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager=(YNHttpTool *)@"YNHttpTool";
        sharedManager = [YNHttpTool new];
        manager = [AFHTTPSessionManager manager];
    });
    //防止子类使用
    NSString *classString = NSStringFromClass([self class]);
    if ([classString isEqualToString:@"YNHttpTool"]==NO) {
        NSParameterAssert(nil);
    }
    return sharedManager;
}

//get
-(void)getPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))rblock andError:(void(^)(NSError *error))eblock{
    
    void(^_grblock)(id relust) = [rblock copy];
    void(^_geblock)(NSError *error) = [eblock copy];
    
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html", nil];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    path = [NSString stringWithFormat:@"%@%@",[self getApiUrl],path];
    
    [self setHeader:manager parameter:parameters];
    
    [manager GET:path parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            _grblock(json);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        _geblock(error);
    }];
}

//POST 请求
- (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void(^)(id relust))rblock andError:(void(^)(NSError *error))eblock{
    
    void(^_rblock)(id relust) = [rblock copy];
    void(^_eblock)(NSError *error) = [eblock copy];
    
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html", nil];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    path = [NSString stringWithFormat:@"%@%@",[self getApiUrl],path];
    
    
    [self setHeader:manager parameter:parameters];
    
    [manager POST:path parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if (json) {
            _rblock(json);
        }else{
            _rblock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        _eblock(error);
        //        [self requestErrorPrompt:NSLocalizedString(@"网络不给力~", nil) andImage:@"picture_no_network_prompt"];
    }];
}

- (NSString *)getApiUrl{
    //[[NSUserDefaults standardUserDefaults] objectForKey:@"CurrentBaseUrl"]
    return @"";
}



-(void)setHeader:(AFHTTPSessionManager *)manager parameter:(NSDictionary *)parameter{
    
    [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"ID"] forHTTPHeaderField:@"userId"];
    [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"system"];
    [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] forHTTPHeaderField:@"token"];
    
    
    
    NSArray *keysArray = [parameter allKeys];
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray  = [keysArray sortedArrayUsingComparator:sort];
    
    NSString *sign = @"";
    for (int i=0; i<resultArray.count; i++) {
        NSString *valueStr= [parameter objectForKey:resultArray[i]];
        NSString *together = [NSString stringWithFormat:@"%@%@%@",resultArray[i],valueStr,securityCode];
        sign = [NSString stringWithFormat:@"%@%@",sign,together];
    }
    
    if (keysArray.count ==0) {
        sign = securityCode;
    }
    
    [manager.requestSerializer setValue:[self md5:sign] forHTTPHeaderField:@"sign"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    app_Version = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
    [manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"]; //版本号
    [manager.requestSerializer setValue:[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] forHTTPHeaderField:@"uuid"];
    
}


- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


@end
